/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.internal.timer;

import com.github.florent37.camerafragment.internal.utils.DateTimeUtils;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 倒计时任务
 *
 * @since 2021-05-25
 */
public class CountdownTask extends TimerTaskBase implements Runnable {
    private static final int CONSTANT_1000 = 1000;
    private int maxDurationMilliseconds = 0;

    /**
     * 构造函数
     *
     * @param callback 倒计时回调
     * @param maxDurationMilliseconds 视频时长
     */
    public CountdownTask(Callback callback, int maxDurationMilliseconds) {
        super(callback);
        this.maxDurationMilliseconds = maxDurationMilliseconds;
    }

    @Override
    public void stop() {
        if (callback != null) {
            callback.setTextVisible(false);
        }
        isAlive = false;
    }

    /**
     * 开始计时
     */
    @Override
    public void start() {
        isAlive = true;
        recordingTimeSeconds = maxDurationMilliseconds / CONSTANT_1000;
        if (callback != null) {
            callback.setText(
                String.format(Locale.getDefault(),
                    "%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(maxDurationMilliseconds),
                    TimeUnit.MILLISECONDS.toSeconds(maxDurationMilliseconds)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(maxDurationMilliseconds))
                ));
            callback.setTextVisible(true);
        }
        handler.postTask(this, DateTimeUtils.SECOND);
    }

    @Override
    public void run() {
        recordingTimeSeconds--;

        int millis = (int) recordingTimeSeconds * CONSTANT_1000;

        if (callback != null) {
            callback.setText(
                String.format(Locale.getDefault(),
                    "%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(millis),
                    TimeUnit.MILLISECONDS.toSeconds(millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
                ));
        }

        if (isAlive && recordingTimeSeconds > 0) {
            handler.postTask(this, DateTimeUtils.SECOND);
        }
    }
}
